package com.shuiyun.jtt.thread;

import com.shuiyun.jtt.enums.JT808;
import com.shuiyun.jtt.message.JTMessage;
import io.netty.channel.Channel;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author shuiyun
 * @program device-simulator
 * @description 心跳线程
 * @date 2022-04-23 16:49
 **/
public class HeartbeatThead extends Thread {

    private final Channel channel;
    private final String mobileNo;
    private final AtomicInteger serialNo;

    public HeartbeatThead(Channel channel, String mobileNo) {
        this.channel = channel;
        this.mobileNo = mobileNo;
        serialNo = new AtomicInteger(1);
    }

    @Override
    public void run() {
        while (true) {
            int serial = serialNo.incrementAndGet();
            if (serial > Integer.MAX_VALUE - 10) {
                serialNo.set(1);
            }
            JTMessage message = new JTMessage();
            message.setHeader(JT808.终端心跳0x0002, mobileNo, serial);
            channel.writeAndFlush(message);

            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
